<?php

namespace app\models\Child;

use Yii;

/**
 * This is the model class for table "t_coupon_usr_rel".
 *
 * @property integer $rel_id
 * @property integer $user_id
 * @property integer $coupon_id
 * @property string $coupon_createtime
 * @property integer $is_used
 * @property string $use_time
 */
class TCouponUsrRel extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 't_coupon_usr_rel';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'coupon_id', 'is_used'], 'integer'],
            [['coupon_createtime', 'use_time'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'rel_id' => 'Rel ID',
            'user_id' => 'User ID',
            'coupon_id' => 'Coupon ID',
            'coupon_createtime' => 'Coupon Createtime',
            'is_used' => 'Is Used',
            'use_time' => 'Use Time',
        ];
    }
    
    /*
     * 获取用户剩余优惠卷数量
     */
    public function getCouponsCount($user_id)
    {
        $coupons = $this->find()
                    ->where(['user_id' => $user_id,'is_used' => 0])
                    ->count();
        return $coupons;
    }
    
    /*
     * 获取用户优惠卷列表
     */
    public function getList($user_id)
    {
        $list = $this->find()
                ->select('subclinic_name,type_name,card_name,discount_desc')
                ->join('left join','sys_discount_card_info','sys_discount_card_info.card_id = t_coupon_usr_rel.coupon_id')
                ->join('left join','sys_discount_card_type','sys_discount_card_type.type_id = sys_discount_card_info.card_type')
                ->join('left join','t_subclinic_info','t_subclinic_info.subclinic_id = sys_discount_card_info.subclinic_ids')
                ->where(['t_coupon_usr_rel.user_id' => $user_id,'is_used' => 0])
                ->asArray()
                ->all();
        
        return $list;
                
    }
    
}
